package com.surelution.projects.congress

import java.text.SimpleDateFormat

class GateController {

    def index = { }
	
	def timers = {
		def timers = CheckInTimer.list()
		
		response.addHeader("Cache-Control", "no-cache")
		
		withFormat {
			xml {
				render(contentType:"text/xml") {
					result() {
						if(timers) {
							timers.each {t->
								timer() {
									def tip = t.ip
									def tno = t.no
									def tid = t.id
									id(tid)
									ip(tip)
									no(tno)
								}
							}
						}
					}
				}
			}
		}
	}
	
	def checkIn = {
		//result:client-id,timer-ip,member-id,time(yyyyMMddHHmmss)
		def sdf = new SimpleDateFormat("yyyyMMddHHmmss")
		def result = params.result
		print "result:"
		println result
		if(result) {
			println "get here"
			String[] lines = result.split("\n");
			println lines.length
			if(lines) {
				for(String line:lines) {
					String[] words = line.split(",");
					println "\n\n"
					println words.length
					if(words.length == 4) {
						def timerIp = words[1]
						def timer = CheckInTimer.findByIp(timerIp)
						def member = Member.get(words[2])
						CheckIn checkIn = new CheckIn()
						checkIn.clientId = words[0]
						checkIn.timer = timer
						checkIn.member = member
						def time = sdf.parse(words[3])
						checkIn.checkInTime = time
				        println checkIn
						checkIn.save(flush:true)
					}
				}
			}
		}
		
	}
	
	def members = {
		response.addHeader("Cache-Control", "no-cache")
		def ms = Member.list()
		withFormat {
			xml {
				render(contentType:"text/xml") {
					result() {
						if(ms) {
							ms.each {m->
								member() {
									id(m.id)
									passportId(m.passportId)
									name(m.name)
									isStanding(m.level.id)
									mobileNumber(m.mobileNumber)
								}
							}
						}
					}
				}
			}
		}
	}
}
